package master;

import java.util.HashMap;
import java.util.Map;

/**
 * @author chenyw
 * @date 2022/8/5 11:22
 */
public class M105buildTree {
    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        for (int i = 0; i < preorder.length; i++) {
            map.put(inorder[i], i);
        }
        Integer mid = map.get(inorder[0]);
        return dfs(preorder, inorder, 0, preorder.length - 1, 0, inorder.length - 1);
    }
    private TreeNode dfs(int[] preorder, int[] inorder, int pre_left, int pre_right, int order_left, int order_right) {
        if (pre_left > pre_right) {
            return null;
        }
//        int val = preorder[pre_left];
//        TreeNode root = new TreeNode(val);
        int order_root_index = map.get(preorder[pre_left]);
        int left_size = order_root_index - order_left;
        TreeNode root = new TreeNode(preorder[pre_left]);
//        int right_size = pre_right - root_index;
        //递归构建左节点
        root.left = dfs(preorder, inorder, pre_left + 1, pre_left + left_size, order_left, order_root_index - 1);
        //递归构建右节点
        root.right = dfs(preorder, inorder, pre_left + left_size +1, pre_right, order_root_index + 1, order_right);
        return root;
    }
}
